<?php
/**
 * Created by PhpStorm.
 * User: Aliaksei Lazerka
 * Date: 10/7/14
 * Time: 5:07 PM
 */

namespace controller;

if (!defined('NYMPH_ROOT')) {
  define('NYMPH_ROOT', dirname("../../" . __FILE__));
  require(NYMPH_ROOT . '/local/loader/kernel/classes/URLClassLoader.php');
}


class Controller
{

  /**
   * @var Controller
   */
  private static $controllerInstance = null;

  /**
   * Hidden constructor
   */
  private function __construct()
  {

  }

  /**
   * Create instance
   */
  public static function getControllerInstance()
  {
    if (self::$controllerInstance == null) {
      self::$controllerInstance = new Controller();
    }
    return self::$controllerInstance;
  }

  /**
   * @var WebParserImpl
   */
  private $parser;

  /**
   * @var array WebConfig
   */
  private $config;

  /**
   * @return array
   */
  public function getConfig()
  {
    return $this->config;
  }

  /**
   * @param array $config
   */
  public function setConfig($config)
  {
    $this->config = $config;
  }

  /**
   * @param WebConfig $config
   */
  public function addConfig($config)
  {
    $this->config[] = $config;
  }

  /**
   * @param string $name action name
   * @return WebConfig configured data for this action
   */
  function getAction($name)
  {
    if ($this->config == null) {
      $this->config = $this->getParser()->parseAll();
    }
    if ($this->config[$name] != null) {
      return $this->config[$name];
    } else {
      return null;
    }


  }

  /**
   * @return WebParserImpl
   */
  public function getParser()
  {
    return $this->parser;
  }

  /**
   * @param WebParserImpl $parser
   */
  public function setParser($parser)
  {
    $this->parser = $parser;
  }

  /**
   * @return array
   */
  public static function getActionAndFunctionFromUrl()
  {
    $result = array();
    $key = array_keys($_GET);
    $key = $key[0];
    $actionEndPos = strpos($key, "$");
    if (!$actionEndPos) {
      $result['action'] = $key;
    } else {
      $result['action'] = substr($key, 0, $actionEndPos);
      $result['function'] = substr($key, $actionEndPos + 1);
    }
    return $result;
  }

}